Vue.directive("drag", {
    inserted: function (el, binding) {
        el.style.position = "absolute";
        let offsetX;
        let offsetY;
        let parentLeft = el.offsetParent.offsetLeft;
        let parentTop = el.offsetParent.offsetTop;
        let maxLeft = el.offsetParent.offsetWidth - el.offsetWidth;
        let maxTop = el.offsetParent.offsetHeight - el.offsetHeight;

        // 鼠标按下的函数
        function mousedownFn(event) {
            let e = event || window.event;
            offsetX = e.offsetX
            offsetY = e.offsetY
            // onmousemove
            // offsetParent: 找到最近的有定位属性的那个元素
            el.offsetParent.addEventListener("mousemove", mousemoveFn);
        };

        // 鼠标移动的函数
        function mousemoveFn(event) {
            let e = event || window.event;
            // 一、数据处理
            let left1 = e.pageX - parentLeft - offsetX;
            let top1 = e.pageY - parentTop - offsetY;
            if (left1 < 0) {
                left1 = 0;
            }
            if (left1 > maxLeft) {
                left1 = maxLeft;
            }
            if (top1 < 0) {
                top1 = 0;
            }
            if (top1 > maxTop) {
                top1 = maxTop;
            }
            // 二、外观呈现
            el.style.left = left1 + "px";
            el.style.top = top1 + "px";
        }

        // onmousedown
        el.addEventListener("mousedown", mousedownFn);

        // onmouseup
        document.addEventListener("mouseup", function () {
            el.offsetParent.removeEventListener("mousemove", mousemoveFn);
        });

    }
    }
);
